import React, {Component,} from 'react';
import {Card, Form, Button, Input, Table, Space, Modal, message, Upload, Select} from 'antd';
import {SearchOutlined, DeleteOutlined, FileAddOutlined, DownloadOutlined,
  UploadOutlined, EditOutlined, RedoOutlined} from '@ant-design/icons';
import styles from './style.module.less';
import {connect} from 'react-redux';
import Highlighter from "react-highlight-words"

const itemStyle = {
  margin: ' 0 0.5rem 0.6rem' 
}

const formLayout = {
  labelCol: { xs: 4, sn: 4 },
  wrapperCol: { xs: 24, sm: 20 }
}

// const grade = ['2016', '2017', '2018', '2019']

const modalTitle = ['', '选择教师', '编辑']

const CollectionCreateForm = ({ visible, onCreate, onCancel, type, record ,teacherList}) => {
  const [form] = Form.useForm();
  form.setFieldsValue({...record,
    teacherId:record.planVO?record.planVO.cardId:"",
    term:record.planVO?record.planVO.term:""
  })
  
  const onOK = () => {
    form
    .validateFields()
    .then((values) => {
      form.resetFields();
      onCreate(values, record);
    })
    .catch((info) => {
      
    });
  }
  return(
    <Modal
      title = {modalTitle[type]}
      onCancel = {onCancel}
      onOk = {onCreate}
      visible = {visible}
      onOk = {onOK}
    >
        <Form 
          {...formLayout}
          // initialValues={records} 默认值，动态值用setFieldsValue
          form={form}
        >
          <Form.Item name='courseName' label='课程名' rules={[
            {required: true, message: '请输入学生学号'}
          ]}><Input disabled /></Form.Item>
          <Form.Item name='term' label='学期' defaultValue={record.planVO?record.planVO.term:""} rules={[
            {required: true, message: '请选择学期'}
          ]}>
            <Select>
              <Select.Option value={1}>
                第一学期
              </Select.Option>
              <Select.Option value={2}>
                第二学期
              </Select.Option>
              <Select.Option value={3}>
                第三学期
              </Select.Option>
              <Select.Option value={4}>
                第四学期
              </Select.Option>
              <Select.Option value={5}>
                第五学期
              </Select.Option>
              <Select.Option value={6}>
                第六学期
              </Select.Option>
              <Select.Option value={7}>
                第七学期
              </Select.Option>
              <Select.Option value={8}>
                第八学期
              </Select.Option>
            </Select>
          </Form.Item>
          <Form.Item name='teacherId' label='任课教师' defaultValue={record.planVO?record.planVO.cardId:""} rules={[
            {required: true, message: '请选择任课教师'}
            ]}>
            <Select loading={teacherList.length == 0}>
              {teacherList.map(item => {

                return <Select.Option value={item.cardId} key={item.userId}>
                  {item.cardId+'-'+item.name}
                </Select.Option>
              })}
            </Select>
          </Form.Item>
          {/* <Form.Item name='phone' label='手机号码' rules={[
            {required: true, message: '请输入学生联系方式'}
          ]}><Input /></Form.Item>
          <Form.Item name='email' label='电子邮箱' rules={[
            {required: true, message: '请输入学生学号'}
          ]}><Input /></Form.Item> */}
          {/* <Form.Item name='grade' label='年级' rules={[
            {required: true, message: '请输入选择年级'}
          ]}>
            <Select>
              {
                grade.map( item => <Select.Option key={item} value={item}>{item}级</Select.Option>)
              }
            </Select>
          </Form.Item> */}
        </Form>
    </Modal>
  )
}

class TeachingProgram extends Component {
  
  state = {
    selectedRowKeys: [],
    visible: false,
    type: 1, // 1为新增 2为编辑
    record: {
      id: "", name: "", tel: "", email: ""
    },
  }
  searchText={
    courseName:"",
    stuNo:""
  }
  
  
  componentDidMount() {
    const {fetch,getTeacher} = this.props;
    localStorage.getItem("grade") ? fetch({grade: localStorage.getItem("grade")}) : message.error("年级设置错误")
    getTeacher({})
  }

  deleteOne = ( record ) => {
    const {deleteStudent} = this.props;
    
    deleteStudent([record.id])
  }

  deleteRow = () => {
    
    const {deleteStudent} = this.props;
    const {selectedRowKeys} = this.state;
    deleteStudent(selectedRowKeys)
    this.setState({
      selectedRowKeys: []
    })
  }

  rowSelection = {
    onChange: (selectedRowKeys, selectedRows) => {
      
      this.setState({
        selectedRowKeys: selectedRowKeys
      })
    },
    getCheckboxProps: record => ({
      disabled: record.name === 'Disabled User', // Column configuration not to be checked
      name: record.name,
    })
  };

  onCreate = (values,record) => {
    
    const { addPlan, editPlan} = this.props;
    const { type } = this.state;
    this.hiddenModal()
    
    if(type == 1) {
      values.majorCourseId = record.majorCourseId
      addPlan({...values})
    } else {
      values.majorCourseId = record.majorCourseId
      values.planId = record.planVO.planId
      
      editPlan({...values})
    }
    // this.setState({
    //   visible: false
    // })
    // add(values)
  }

  hiddenModal = () => {
    this.setState({
      visible: false
    })
  }

  add = (record) => {
    this.setState({
      visible: true,
      type: 1,
      record: record
    })
  }

  edit = (record) => {
    
    this.setState({
      visible: true,
      type: 2,
      record: record
    })
  }

  search = () => {
    this.setState({})
  }
  render(){
    const {visible, type, record, selectedRowKeys} = this.state;
    const store = this.props.store;
    console.log(store)
    const columns = [
      {
        // title: '学期',
        // dataIndex: 'term',
        // key: 'term',
        // filteredValue:[this.searchText.stuNo],
        // onFilter: (value, record) => 
        //             record.stuNo
        //               .toString()
        //               .includes(value),
        // render:(text) => {
        //   return <Highlighter
        //     highlightStyle={{ backgroundColor: '#ffc069', padding: 0 }}
        //     searchWords={[this.searchText.stuNo]}
        //     autoEscape
        //     textToHighlight={text?text.toString():''}
        //   />
        // }
      },
      {
        title: '专业',
        dataIndex: 'courseName',
        key: 'courseName',
        filteredValue:[this.searchText.courseName],
        onFilter: (value, record) =>
                    record.courseName
                      .toString()
                      .includes(value),
        render:(text) => {
          return <Highlighter
            highlightStyle={{ backgroundColor: '#ffc069', padding: 0 }}
            searchWords={[this.searchText.courseName]}
            autoEscape
            textToHighlight={text?text.toString():''}
          />
        }
      },
      {
        title: '负责教师',
        dataIndex: 'majorCourseStatus',
        key: 'majorCourseStatus',
        render:(value,record) => {
          // 
          return value? <Button type="link">{record.planVO.teacherName}</Button> : <Button type="link" danger>未分配</Button>
        }
      },
      // {
      //   title: '当前状态',
      //   dataIndex: 'majorCourseStatus',
      //   key: 'majorCourseStatus',
      //   render: (value) => {
      //     return value? "已分配":"未分配"
      //   }
      // },
      // {
      //   title: '年级',
      //   dataIndex: 'grade',
      //   key: 'grade'
      // },
      {
        title: '操作',
        render:  (record) => {
          // 
          return <Space size="middle">
            {record.majorCourseStatus?<a onClick={ () => this.edit(record)}><EditOutlined />编辑</a>:<a onClick={ () => this.add(record)}><EditOutlined />选择教师</a>}
            {/* <a onClick = { () => {this.deleteOne(record)}} className="ant-dropdown-link">
              <DeleteOutlined /> 删除
            </a> */}
            {/* <a className="ant-dropdown-link">
              <RedoOutlined />重置 
            </a> */}
          </Space>
        }
      },
    ]
    
    return(
      <Card title = {
        <div className = { styles.tableOptions }>
          <div style={itemStyle} className = {`${styles.inputItem}`} >
            <span>学号</span>
            <Input onChange={(e) => this.searchText.stuNo = e.target.value}/>
          </div>
          <div style={itemStyle} className = {`${styles.inputItem}`}>
            <span>姓名</span>
            <Input onChange={(e) => this.searchText.name = e.target.value}/>
          </div>
          <Button className={styles.normal} disabled={store.loading} icon={<SearchOutlined />} type='primary' style={itemStyle} onClick={this.search}>搜索</Button>
            
          <Button className={styles.normal} disabled={store.loading} icon={<DeleteOutlined />} type='primary' style={itemStyle} onClick={
            () => {
              this.searchText.name = ""
              this.searchText.stuNo = ""
              this.search()
            }
          }>清空搜索</Button>
          <Button className={styles.add} disabled={store.loading} icon={<FileAddOutlined />} type='primary' onClick={this.add} style={itemStyle}>新增</Button>
          <Upload beforeUpload={(file) => {
            
            this.props.uploadFile({
              file:file
            })
            return false
          }}
            itemRender={() => null}
            disabled={store.loading}
          >
            <Button className={styles.normal} disabled={store.loading} type='primary' icon={<UploadOutlined />} style={itemStyle}>上传模板</Button>
          </Upload>  
          <Button icon={<DownloadOutlined />} style={itemStyle}>下载模板</Button>
        </div>
      }>
        {/* <Test list = {store.list}/> */}
        <Table 
          // rowSelection={{
          //   selectedRowKeys: selectedRowKeys,
          //   ...this.rowSelection,
          // }}
          dataSource = {store.planList}
          columns={columns}
          loading = {store.loading}
          rowKey='stuId'
        />


        <CollectionCreateForm record={record} type={type} visible = {visible} onCreate={this.onCreate} onCancel={this.hiddenModal} teacherList={store.teacherList}/>
      </Card>
    )
  }
} 

const mapStateToProps = ({teachingProgram}) => ({
  store: teachingProgram
})

const mapDispatchToProps = dispatch => ({
  add: dispatch.teachingProgram.add,
  update: dispatch.teachingProgram.update,
  deleteStudent: dispatch.teachingProgram.delete,
  uploadFile: dispatch.teachingProgram.uploadFile,
  
  fetch: dispatch.teachingProgram.fetch,
  addPlan:dispatch.teachingProgram.addPlan,
  getTeacher: dispatch.teachingProgram.getTeacher,
  editPlan:dispatch.teachingProgram.editPlan,
})

export default connect(
  mapStateToProps, 
  mapDispatchToProps
)(TeachingProgram);